package com.san.common.auth.service.impl;

import cn.hutool.core.lang.Validator;
import com.san.common.auth.dto.LoginSysUser;
import com.san.common.auth.entity.SysUser;
import com.san.common.auth.service.UserService;
import com.san.common.auth.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author zhoubin
 * @since 1.0.0
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	UserService userService;


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		System.out.println("执行自定义登录逻辑");

		//1.根据用户名去数据库查询，如果不存在抛UsernameNotFoundException异常
		final LoginSysUser loginUser;
		SysUser user = Validator.isEmail(username) ? userService.getUserByEmailNotNull(username) :
				userService.getUserByUsernameNotNull(username);
		loginUser = UserUtils.getLoginSysUser(user);

		//2.比较密码（注册时已经加密过），如果匹配成功返回UserDetails
		return loginUser;
//		return new loginUser(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_abc,/main.html,/insert,/delete"));
	}
}